package com.ash.android_adk_demo
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ash.base.bean.HcResult
import com.ash.base.logd
import com.ash.base.loge
import com.ash.base.repository.BaseRepository
import com.ash.android_adk_demo.ScheduleAdapter
import com.google.gson.Gson
import com.hc.schedule.model.Schedule
import com.hc.schedule.service.ScheduleService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ScheduleActivity : ComponentActivity(), OnClickListener {
    private var mRecycler: RecyclerView? = null
    private var statusTextView: TextView? = null
    private lateinit var scheduleAdapter: ScheduleAdapter
    private val scheduleList = mutableListOf<Schedule>()
    
    fun bindClick() {
        statusTextView = findViewById(R.id.tv_status_schedule)
        mRecycler = findViewById(R.id.recycler_schedule)
        findViewById<Button>(R.id.btn_fetch_all).setOnClickListener(this)
    }


    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_schedule)
        bindClick()
        setupRecyclerView()
    }

    override fun onResume() {
        super.onResume()
        try {
            statusTextView?.text = "Status: 正在加载数据..."
            GlobalScope.launch {
                try {
                    val scheduleService = ScheduleService()
                    var userId = BaseRepository(this@ScheduleActivity).getUserUUID()
                    var ret = scheduleService.fetchAll(userId.toString(), this@ScheduleActivity)

                    withContext(Dispatchers.Main) {
                        if (ret is HcResult.Success) {
                            var datas = ret.data as MutableList<Schedule>
                            scheduleList.clear()
                            scheduleList.addAll(datas)
                            scheduleAdapter.updateData(scheduleList)
                            statusTextView?.text = "Status: 加载成功"
                            "加载成功，共 ${datas.size} 条数据".logd()
                        } else if (ret is HcResult.Error) {
                            statusTextView?.text = "Status: 加载失败 - ${ret.mess}"
                            ret.mess.loge()
                        }
                    }
                }catch (e: Exception) {
                    statusTextView?.text = "Status: 加载异常 - ${e.message}"
                    "${e.message} ${e.stackTraceToString()}".logd()
                }
            }

        } catch (e: Exception) {
            statusTextView?.text = "Status: 加载异常 - ${e.message}"
            "${e.message} ${e.stackTraceToString()}".logd()
        }
    }
    
    @RequiresApi(Build.VERSION_CODES.O)
    private fun setupRecyclerView() {
        scheduleAdapter = ScheduleAdapter(scheduleList)
        mRecycler?.apply {
            layoutManager = LinearLayoutManager(this@ScheduleActivity)
            adapter = scheduleAdapter
        }

        scheduleAdapter.setOnItemClickListener { schedule ->
            // 查看详情按钮点击事件
            var intent = Intent(this, ScheduleDetailActivity::class.java)
            intent.putExtra(
                ScheduleDetailActivity.EXTRA_SCHEDULE_DATA, Gson().toJson(schedule))
            startActivity(intent)
                showToast("查看详情: ${schedule.name}\n")

            "查看详情按钮点击: ${schedule.name}".logd()
        }
    }




    override fun onClick(v: View?) {
        when(v?.id){
            R.id.btn_fetch_all -> {
                try {
                    statusTextView?.text = "Status: 正在加载数据..."
                    GlobalScope.launch {
                        val scheduleService = ScheduleService()
                        var userId = BaseRepository(this@ScheduleActivity).getUserUUID()
                        var ret = scheduleService.fetchAll(userId.toString(), this@ScheduleActivity)
                        
                        withContext(Dispatchers.Main) {
                            if (ret is HcResult.Success) {
                                var datas = ret.data as MutableList<Schedule>
                                scheduleList.clear()
                                scheduleList.addAll(datas)
                                scheduleAdapter.updateData(scheduleList)
                                statusTextView?.text = "Status: 加载成功"
                                "加载成功，共 ${datas.size} 条数据".logd()
                            } else if (ret is HcResult.Error) {
                                statusTextView?.text = "Status: 加载失败 - ${ret.mess}"
                                ret.mess.loge()
                                    showToast(
                                        "加载失败: ${ret.mess}"
                                    )
                                }
                        }
                    }
                } catch (e: Exception) {
                    statusTextView?.text = "Status: 加载异常 - ${e.message}"
                    "${e.message} ${e.stackTraceToString()}".logd()
                        showToast(
                            "加载异常: ${e.message}"
                        )
                }
            }
        }
    }
}